import Vue from "vue";
import Router from "vue-router";
import {
  Home,
  HomePage,
  Article,
  Personal,
  Category,
  User,
  ArticleAdd,
  Edit,
  Login,
  PresonalAdd,
  EditPersonal
} from "../view/index";
// 在router中无法使用elementUI弹窗，只能单独引入
import "element-ui/lib/theme-chalk/index.css";
import { Message } from "element-ui";

Vue.use(Router);

const originalPush = Router.prototype.push;
Router.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err);
};
const router = new Router({
  routes: [
    {
      path: "/",
      component: Home,
      children: [
        {
          path: "/",
          component: HomePage
        },
        {
          path: "/article",
          component: Article
        },
        {
          path: "/personal",
          component: Personal
        },
        {
          path: "/category",
          component: Category
        },
        {
          path: "/user",
          component: User
        },
        {
          path: "/articleadd",
          component: ArticleAdd
        },
        {
          path: "/presonalAdd",
          component: PresonalAdd
        },
        {
          path: "/edit",
          component: Edit
        },
        {
          path: "/editPersonal",
          component: EditPersonal
        }
      ]
    },
    {
      path: "/login",
      component: Login
    },
    {
      path: "*",
      redirect: "/"
    }
  ]
});
router.beforeEach((to, from, next) => {
  let user = JSON.parse(sessionStorage.getItem("user"));
  if (user === null) {
    if (to.path != "/login") {
      next("/login");
    } else {
      next();
    }
  } else {
    // 判断登陆后是否要返回登陆界面
    if (to.path == "/login") {
      Message.warning("退出后才可返回登陆界面");
      next("/");
    } else {
      next();
    }
  }
});

export { router };
